home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / perl5 / XML / XPath.pm < prev   
Text File  |  2003-01-26  |  17KB  |  554 lines

  1. # $Id: XPath.pm,v 1.56 2003/01/26 19:33:17 matt Exp $
  2.  
  3. package XML::XPath;
  4.  
  5. use strict;
  6. use vars qw($VERSION $AUTOLOAD $revision);
  7.  
  8. $VERSION = '1.13';
  9.  
  10. $XML::XPath::Namespaces = 1;
  11. $XML::XPath::Debug = 0;
  12.  
  13. use XML::XPath::XMLParser;
  14. use XML::XPath::Parser;
  15. use IO::File;
  16.  
  17. # For testing
  18. #use Data::Dumper;
  19. #$Data::Dumper::Indent = 1;
  20.  
  21. # Parameters for new()
  22. my @options = qw(
  23.         filename
  24.         parser
  25.         xml
  26.         ioref
  27.         context
  28.         );
  29.  
  30. sub new {
  31.     my $proto = shift;
  32.     my $class = ref($proto) || $proto;
  33.  
  34.     my(%args);
  35.     # Try to figure out what the user passed
  36.     if ($#_ == 0) { # passed a scalar
  37.         my $string = $_[0];
  38.         if ($string =~ m{<.*?>}s) { # it's an XML string
  39.             $args{'xml'} = $string;
  40.         } elsif (ref($string)) {    # read XML from file handle
  41.             $args{'ioref'} = $string;
  42.         } elsif ($string eq '-') {  # read XML from stdin
  43.             $args{'ioref'} = IO::File->new($string);
  44.         } else {                    # read XML from a file
  45.             $args{'filename'} = $string;
  46.         }
  47.     } else {        # passed a hash or hash reference
  48.         # just pass the parameters on to the XPath constructor
  49.         %args = ((ref($_[0]) eq "HASH") ? %{$_[0]} : @_);
  50.     }
  51.  
  52.     if ($args{filename} && (!-e $args{filename} || !-r $args{filename})) {
  53.         die "Cannot open file '$args{filename}'";
  54.     }
  55.     my %hash = map(( "_$_" => $args{$_} ), @options);
  56.     $hash{path_parser} = XML::XPath::Parser->new();
  57.     return bless \%hash, $class;
  58. }
  59.  
  60. sub find {
  61.     my $self = shift;
  62.     my $path = shift;
  63.     my $context = shift;
  64.     die "No path to find" unless $path;
  65.     
  66.     if (!defined $context) {
  67.         $context = $self->get_context;
  68.     }
  69.     if (!defined $context) {
  70.         # Still no context? Need to parse...
  71.         my $parser = XML::XPath::XMLParser->new(
  72.                 filename => $self->get_filename,
  73.                 xml => $self->get_xml,
  74.                 ioref => $self->get_ioref,
  75.                 parser => $self->get_parser,
  76.                 );
  77.         $context = $parser->parse;
  78.         $self->set_context($context);
  79. #        warn "CONTEXT:\n", Data::Dumper->Dumpxs([$context], ['context']);
  80.     }
  81.     
  82.     my $parsed_path = $self->{path_parser}->parse($path);
  83. #    warn "\n\nPATH: ", $parsed_path->as_string, "\n\n";
  84.     
  85. #    warn "evaluating path\n";
  86.     return $parsed_path->evaluate($context);
  87. }
  88.  
  89. # sub memsize {
  90. #     print STDERR @_, "\t";
  91. #     open(FH, '/proc/self/status');
  92. #     while(<FH>) {
  93. #         print STDERR $_ if /^VmSize/;
  94. #     }
  95. #     close FH;
  96. # }
  97. sub findnodes {
  98.     my $self = shift;
  99.     my ($path, $context) = @_;
  100.     
  101.     my $results = $self->find($path, $context);
  102.     
  103.     if ($results->isa('XML::XPath::NodeSet')) {
  104.         return wantarray ? $results->get_nodelist : $results;
  105. #        return $results->get_nodelist;
  106.     }
  107.     
  108. #    warn("findnodes returned a ", ref($results), " object\n") if $XML::XPath::Debug;
  109.     return wantarray ? () : XML::XPath::NodeSet->new();
  110. }
  111.  
  112. sub matches {
  113.     my $self = shift;
  114.     my ($node, $path, $context) = @_;
  115.  
  116.     my @nodes = $self->findnodes($path, $context);
  117.  
  118.     if (grep { "$node" eq "$_" } @nodes) {
  119.         return 1;
  120.     }
  121.     return;
  122. }
  123.  
  124. sub findnodes_as_string {
  125.     my $self = shift;
  126.     my ($path, $context) = @_;
  127.     
  128.     my $results = $self->find($path, $context);
  129.     
  130.     if ($results->isa('XML::XPath::NodeSet')) {
  131.         return join('', map { $_->toString } $results->get_nodelist);
  132.     }
  133.     elsif ($results->isa('XML::XPath::Node')) {
  134.         return $results->toString;
  135.     }
  136.     else {
  137.         return XML::XPath::Node::XMLescape($results->value);
  138.     }
  139. }
  140.  
  141. sub findvalue {
  142.     my $self = shift;
  143.     my ($path, $context) = @_;
  144.     
  145.     my $results = $self->find($path, $context);
  146.     
  147.     if ($results->isa('XML::XPath::NodeSet')) {
  148.         return $results->to_literal;
  149.     }
  150.     
  151.     return $results;
  152. }
  153.  
  154. sub exists
  155. {
  156.     my $self = shift;
  157.     my ($path, $context) = @_;
  158.     $path = '/' if (!defined $path);
  159.     my @nodeset = $self->findnodes($path, $context);
  160.     return 1 if (scalar( @nodeset ));
  161.     return 0;
  162. }
  163.  
  164. sub getNodeAsXML {
  165.   my $self = shift;
  166.   my $node_path = shift;
  167.   $node_path = '/' if (!defined $node_path);
  168.   if (ref($node_path)) {
  169.     return $node_path->as_string();
  170.   } else {
  171.     return $self->findnodes_as_string($node_path);
  172.   }
  173. }
  174.  
  175. sub getNodeText {
  176.   my $self = shift;
  177.   my $node_path = shift;
  178.   if (ref($node_path)) {
  179.     return $node_path->string_value();
  180.   } else {
  181.     return $self->findvalue($node_path);
  182.   }
  183. }
  184.  
  185. sub setNodeText {
  186.   my $self = shift;
  187.   my($node_path, $new_text) = @_;
  188.   my $nodeset = $self->findnodes($node_path);
  189.   return undef if (!defined $nodeset); # could not find node
  190.   my @nodes = $nodeset->get_nodelist;
  191.   if ($#nodes < 0) {
  192.     if ($node_path =~ m|/@([^/]+)$|) {
  193.       # attribute not found, so try to create it
  194.       my $parent_path = $`;
  195.       my $attr = $1;
  196.       $nodeset = $self->findnodes($parent_path);
  197.       return undef if (!defined $nodeset); # could not find node
  198.       foreach my $node ($nodeset->get_nodelist) {
  199.         my $newnode = XML::XPath::Node::Attribute->new($attr, $new_text);
  200.         return undef if (!defined $newnode); # could not create new node
  201.         $node->appendAttribute($newnode);
  202.       }
  203.     } else {
  204.       return undef; # could not find node
  205.     }
  206.   }
  207.   foreach my $node (@nodes) {
  208.     if ($node->getNodeType == XML::XPath::Node::ATTRIBUTE_NODE) {
  209.       $node->setNodeValue($new_text);
  210.     } else {
  211.       foreach my $delnode ($node->getChildNodes()) {
  212.         $node->removeChild($delnode);
  213.       }
  214.       my $newnode = XML::XPath::Node::Text->new($new_text);
  215.       return undef if (!defined $newnode); # could not create new node
  216.       $node->appendChild($newnode);
  217.     }
  218.   }
  219.   return 1;
  220. }
  221.  
  222. sub createNode {
  223.   my $self = shift;
  224.   my($node_path) = @_;
  225.   my $path_steps = $self->{path_parser}->parse($node_path);
  226.   my @path_steps = ();
  227.   foreach my $step (@{$path_steps->get_lhs()}) {
  228.     my $string = $step->as_string();
  229.     push(@path_steps, $string) if (defined $string && $string ne "");
  230.   }
  231.   my $prev_node = undef;
  232.   my $nodeset = undef;
  233.   my $nodes = undef;
  234.   my $p = undef;
  235.   my $test_path = "";
  236.   # Start with the deepest node, working up the path (right to left),
  237.   # trying to find a node that exists.
  238.   for ($p = $#path_steps; $p >= 0; $p--) {
  239.     my $path = $path_steps[$p];
  240.     $test_path = "(/" . join("/", @path_steps[0..$p]) . ")";
  241.     $nodeset = $self->findnodes($test_path);
  242.     return undef if (!defined $nodeset); # error looking for node
  243.     $nodes = $nodeset->size;
  244.     return undef if ($nodes > 1); # too many paths - path not specific enough
  245.     if ($nodes == 1) { # found a node -- need to create nodes below it
  246.       $prev_node = $nodeset->get_node(1);
  247.       last;
  248.     }
  249.   }
  250.   if (!defined $prev_node) {
  251.     my @root_nodes = $self->findnodes('/')->get_nodelist();
  252.     $prev_node = $root_nodes[0];
  253.   }
  254.   # We found a node that exists, or we'll start at the root.
  255.   # Create all lower nodes working left to right along the path.
  256.   for ($p++ ; $p <= $#path_steps; $p++) {
  257.     my $path = $path_steps[$p];
  258.     my $newnode = undef;
  259.     my($axis,$name) = ($path =~ /^(.*?)::(.*)$/);
  260.     if ($axis =~ /^child$/i) {
  261.       $newnode = XML::XPath::Node::Element->new($name);
  262.       return undef if (!defined $newnode); # could not create new node
  263.       $prev_node->appendChild($newnode);
  264.     } elsif ($axis =~ /^attribute$/i) {
  265.       $newnode = XML::XPath::Node::Attribute->new($name, "");
  266.       return undef if (!defined $newnode); # could not create new node
  267.       $prev_node->appendAttribute($newnode);
  268.     }
  269.     $prev_node = $newnode;
  270.   }
  271.   return $prev_node;
  272. }
  273.  
  274. sub get_filename {
  275.     my $self = shift;
  276.     $self->{_filename};
  277. }
  278.  
  279. sub set_filename {
  280.     my $self = shift;
  281.     $self->{_filename} = shift;
  282. }
  283.  
  284. sub get_parser {
  285.     my $self = shift;
  286.     $self->{_parser};
  287. }
  288.  
  289. sub set_parser {
  290.     my $self = shift;
  291.     $self->{_parser} = shift;
  292. }
  293.  
  294. sub get_xml {
  295.     my $self = shift;
  296.     $self->{_xml};
  297. }
  298.  
  299. sub set_xml {
  300.     my $self = shift;
  301.     $self->{_xml} = shift;
  302. }
  303.  
  304. sub get_ioref {
  305.     my $self = shift;
  306.     $self->{_ioref};
  307. }
  308.  
  309. sub set_ioref {
  310.     my $self = shift;
  311.     $self->{_ioref} = shift;
  312. }
  313.  
  314. sub get_context {
  315.     my $self = shift;
  316.     $self->{_context};
  317. }
  318.  
  319. sub set_context {
  320.     my $self = shift;
  321.     $self->{_context} = shift;
  322. }
  323.  
  324. sub cleanup {
  325.     my $self = shift;
  326.     if ($XML::XPath::SafeMode) {
  327.         my $context = $self->get_context;
  328.         return unless $context;
  329.         $context->dispose;
  330.     }
  331. }
  332.  
  333. sub set_namespace {
  334.     my $self = shift;
  335.     my ($prefix, $expanded) = @_;
  336.     $self->{path_parser}->set_namespace($prefix, $expanded);
  337. }
  338.  
  339. sub clear_namespaces {
  340.     my $self = shift;
  341.     $self->{path_parser}->clear_namespaces();
  342. }
  343.  
  344. 1;
  345. __END__
  346.  
  347. =head1 NAME
  348.  
  349. XML::XPath - a set of modules for parsing and evaluating XPath statements
  350.  
  351. =head1 DESCRIPTION
  352.  
  353. This module aims to comply exactly to the XPath specification at
  354. http://www.w3.org/TR/xpath and yet allow extensions to be added in the
  355. form of functions. Modules such as XSLT and XPointer may need to do
  356. this as they support functionality beyond XPath.
  357.  
  358. =head1 SYNOPSIS
  359.  
  360.     use XML::XPath;
  361.     use XML::XPath::XMLParser;
  362.     
  363.     my $xp = XML::XPath->new(filename => 'test.xhtml');
  364.     
  365.     my $nodeset = $xp->find('/html/body/p'); # find all paragraphs
  366.     
  367.     foreach my $node ($nodeset->get_nodelist) {
  368.         print "FOUND\n\n", 
  369.             XML::XPath::XMLParser::as_string($node),
  370.             "\n\n";
  371.     }
  372.  
  373. =head1 DETAILS
  374.  
  375. There's an awful lot to all of this, so bear with it - if you stick it
  376. out it should be worth it. Please get a good understanding of XPath
  377. by reading the spec before asking me questions. All of the classes
  378. and parts herein are named to be synonimous with the names in the
  379. specification, so consult that if you don't understand why I'm doing
  380. something in the code.
  381.  
  382. =head1 API
  383.  
  384. The API of XML::XPath itself is extremely simple to allow you to get
  385. going almost immediately. The deeper API's are more complex, but you
  386. shouldn't have to touch most of that.
  387.  
  388. =head2 new()
  389.  
  390. This constructor follows the often seen named parameter method call.
  391. Parameters you can use are: filename, parser, xml, ioref and context.
  392. The filename parameter specifies an XML file to parse. The xml
  393. parameter specifies a string to parse, and the ioref parameter
  394. specifies an ioref to parse. The context option allows you to 
  395. specify a context node. The context node has to be in the format 
  396. of a node as specified in L<XML::XPath::XMLParser>. The 4 parameters
  397. filename, xml, ioref and context are mutually exclusive - you should
  398. only specify one (if you specify anything other than context, the
  399. context node is the root of your document).
  400. The parser option allows you to pass in an already prepared 
  401. XML::Parser object, to save you having to create more than one
  402. in your application (if, for example, you're doing more than just XPath).
  403.  
  404.     my $xp = XML::XPath->new( context => $node );
  405.  
  406. It is very much recommended that you use only 1 XPath object throughout 
  407. the life of your application. This is because the object (and it's sub-objects)
  408. maintain certain bits of state information that will be useful (such
  409. as XPath variables) to later calls to find(). It's also a good idea because
  410. you'll use less memory this way.
  411.  
  412. =head2 I<nodeset> = find($path, [$context])
  413.  
  414. The find function takes an XPath expression (a string) and returns either an
  415. XML::XPath::NodeSet object containing the nodes it found (or empty if
  416. no nodes matched the path), or one of XML::XPath::Literal (a string),
  417. XML::XPath::Number, or XML::XPath::Boolean. It should always return 
  418. something - and you can use ->isa() to find out what it returned. If you
  419. need to check how many nodes it found you should check $nodeset->size.
  420. See L<XML::XPath::NodeSet>. An optional second parameter of a context
  421. node allows you to use this method repeatedly, for example XSLT needs
  422. to do this.
  423.  
  424. =head2 findnodes($path, [$context])
  425.  
  426. Returns a list of nodes found by $path, optionally in context $context. 
  427. In scalar context returns an XML::XPath::NodeSet object.
  428.  
  429. =head2 findnodes_as_string($path, [$context])
  430.  
  431. Returns the nodes found reproduced as XML. The result is not guaranteed
  432. to be valid XML though.
  433.  
  434. =head2 findvalue($path, [$context])
  435.  
  436. Returns either a C<XML::XPath::Literal>, a C<XML::XPath::Boolean> or a
  437. C<XML::XPath::Number> object. If the path returns a NodeSet,
  438. $nodeset->to_literal is called automatically for you (and thus a
  439. C<XML::XPath::Literal> is returned). Note that
  440. for each of the objects stringification is overloaded, so you can just
  441. print the value found, or manipulate it in the ways you would a normal
  442. perl value (e.g. using regular expressions).
  443.  
  444. =head2 exists($path, [$context])
  445.  
  446. Returns true if the given path exists.
  447.  
  448. =head2 matches($node, $path, [$context])
  449.  
  450. Returns true if the node matches the path (optionally in context $context).
  451.  
  452. =head2 getNodeText($path)
  453.  
  454. Returns the text string for a particular XML node.  Returns a string,
  455. or undef if the node doesn't exist.
  456.  
  457. =head2 setNodeText($path, $text)
  458.  
  459. Sets the text string for a particular XML node.  The node can be an
  460. element or an attribute.  If the node to be set is an attribute, and
  461. the attribute node does not exist, it will be created automatically.
  462.  
  463. =head2 createNode($path)
  464.  
  465. Creates the node matching the path given.  If part of the path given, or
  466. all of the path do not exist, the necessary nodes will be created
  467. automatically.
  468.  
  469. =head2 set_namespace($prefix, $uri)
  470.  
  471. Sets the namespace prefix mapping to the uri.
  472.  
  473. Normally in XML::XPath the prefixes in XPath node tests take their
  474. context from the current node. This means that foo:bar will always
  475. match an element <foo:bar> regardless of the namespace that the prefix
  476. foo is mapped to (which might even change within the document, resulting
  477. in unexpected results). In order to make prefixes in XPath node tests
  478. actually map to a real URI, you need to enable that via a call
  479. to the set_namespace method of your XML::XPath object.
  480.  
  481. =head2 clear_namespaces()
  482.  
  483. Clears all previously set namespace mappings.
  484.  
  485. =head2 $XML::XPath::Namespaces
  486.  
  487. Set this to 0 if you I<don't> want namespace processing to occur. This
  488. will make everything a little (tiny) bit faster, but you'll suffer for it,
  489. probably.
  490.  
  491. =head1 Node Object Model
  492.  
  493. See L<XML::XPath::Node>, L<XML::XPath::Node::Element>, 
  494. L<XML::XPath::Node::Text>, L<XML::XPath::Node::Comment>,
  495. L<XML::XPath::Node::Attribute>, L<XML::XPath::Node::Namespace>,
  496. and L<XML::XPath::Node::PI>.
  497.  
  498. =head1 On Garbage Collection
  499.  
  500. XPath nodes work in a special way that allows circular references, and 
  501. yet still lets Perl's reference counting garbage collector to clean up
  502. the nodes after use. This should be totally transparent to the user,
  503. with one caveat: B<If you free your tree before letting go of a sub-tree,
  504. consider that playing with fire and you may get burned>. What does this
  505. mean to the average user? Not much. Provided you don't free (or let go
  506. out of scope) either the tree you passed to XML::XPath->new, or if you
  507. didn't pass a tree, and passed a filename or IO-ref, then provided you
  508. don't let the XML::XPath object go out of scope before you let results
  509. of find() and its friends go out of scope, then you'll be fine. Even if
  510. you B<do> let the tree go out of scope before results, you'll probably
  511. still be fine. The only case where you may get stung is when the last
  512. part of your path/query is either an ancestor or parent axis. In that
  513. case the worst that will happen is you'll end up with a circular reference
  514. that won't get cleared until interpreter destruction time. You can get
  515. around that by explicitly calling $node->DESTROY on each of your result
  516. nodes, if you really need to do that.
  517.  
  518. Mail me direct if that's not clear. Note that it's not doom and gloom. It's
  519. by no means perfect, but the worst that will happen is a long running process
  520. could leak memory. Most long running processes will therefore be able to
  521. explicitly be careful not to free the tree (or XML::XPath object) before
  522. freeing results. AxKit, an application that uses XML::XPath, does this and
  523. I didn't have to make any changes to the code - it's already sensible
  524. programming.
  525.  
  526. If you I<really> don't want all this to happen, then set the variable
  527. $XML::XPath::SafeMode, and call $xp->cleanup() on the XML::XPath object
  528. when you're finished, or $tree->dispose() if you have a tree instead.
  529.  
  530. =head1 Example
  531.  
  532. Please see the test files in t/ for examples on how to use XPath.
  533.  
  534. =head1 Support/Author
  535.  
  536. This module is copyright 2000 AxKit.com Ltd. This is free
  537. software, and as such comes with NO WARRANTY. No dates are used in this
  538. module. You may distribute this module under the terms of either the
  539. Gnu GPL,  or the Artistic License (the same terms as Perl itself).
  540.  
  541. For support, please subscribe to the Perl-XML mailing list at the URL 
  542. http://listserv.activestate.com/mailman/listinfo/perl-xml
  543.  
  544. Matt Sergeant, matt@sergeant.org
  545.  
  546. =head1 SEE ALSO
  547.  
  548. L<XML::XPath::Literal>, L<XML::XPath::Boolean>, L<XML::XPath::Number>,
  549. L<XML::XPath::XMLParser>, L<XML::XPath::NodeSet>, L<XML::XPath::PerlSAX>,
  550. L<XML::XPath::Builder>.
  551.  
  552. =cut
  553.